package day07;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

//本类利用java反射技术获取成员方法，构造方法
public class Reflection {
    //1.获取指定的修饰权限为public的成员方法
    @Test
    public void getM1() throws Exception {
        //先获取字节码对象
        Class<?> aClass = Class.forName("day07.Person");
        Method eatM = aClass.getMethod("eat", int.class);
        Method playM = aClass.getMethod("play", String.class);
        System.out.println(eatM.getName());
        System.out.println(playM.getName());
    }
    //2.获取所有修饰权限为public的成员方法
    @Test
    public void getM2(){
        //先获取字节码对象
        Person p=new Person();
        Class<?> aClass = p.getClass();
        Method[] methods = aClass.getMethods();
        for (Method m:methods){
            System.out.println(m.getName());//注意这个打印的不仅仅是Person类里定义的修饰权限为public的成员方法
        }
    }
    //3.获取指定的方法
    @Test
    public void getM3() throws Exception {
        //先获取字节码对象
        Class<?> personClass = Person.class;
        Method drinkM = personClass.getDeclaredMethod("drink");
        System.out.println(drinkM.getName());
    }
    //4.获取所有成员方法
    @Test
    public void getM4(){
        //先获取字节码对象
        Class<?> personClass = Person.class;
        Method[] declaredMethods = personClass.getDeclaredMethods();
        for (Method m:declaredMethods){
            System.out.println(m.getName());
        }
    }
    //1.获取指定的修饰权限为public的构造方法，并且根据构造方法创建对象
    @Test
    public void getC1() throws Exception {
        //先获取字节码对象
        Class<?> personClass = Person.class;
        //01.触发全参构造创建对象
        Constructor<?> constructor1 = personClass.getConstructor(String.class, int.class, String.class, String.class);
        Object o1 = constructor1.newInstance("123",12,"78","78");
        System.out.println(o1);
        //02.触发无参构造创建对象
        Constructor<?> constructor2 = personClass.getConstructor();
        Object o2 = constructor2.newInstance();
        System.out.println(o2);
    }
    //2.获取所有修饰权限为public的构造方法
   @Test
    public void getC2(){
       //先获取字节码对象
       Class<?> personClass = Person.class;
       Constructor<?>[] constructors = personClass.getConstructors();
       for (int i = 0; i < constructors.length; i++) {
           System.out.println(constructors[i].getName());
       }
   }
   //3.获取指定的构造方法
    @Test
    public void getC3() throws Exception {
        //先获取字节码对象
        Class<?> personClass = Person.class;
        Constructor<?> declaredConstructor = personClass.getDeclaredConstructor(String.class);
        String name = declaredConstructor.getName();
        System.out.println(name);
    }
    //4.获取所有的构造方法
    @Test
    public void getC4(){
        //先获取字节码对象
        Class<?> personClass = Person.class;
        Constructor<?>[] declaredConstructors = personClass.getDeclaredConstructors();
        for (Constructor c:declaredConstructors){
            System.out.println(c.getName());
        }
    }



}
